package com.eta.common.interceptor;

import com.eta.common.constant.ResultCodeEnum;
import com.eta.common.context.UserContext;
import com.eta.common.entity.po.SysUser;
import com.eta.common.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 星河一叶Ck
 * @date 2025/9/8
 * @description
 */

@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("X-User-Id");
        String userName = request.getHeader("X-User-Name");
        String role = request.getHeader("X-User-Role");

        // 校验请求头（防止绕过网关直接调用服务）
        if (userId == null) {
            throw new BusinessException(ResultCodeEnum.USER_NOT_LOGIN);
        }

        // 组装用户信息， 存入UserContext
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(userId));
        sysUser.setUserName(userName);
        sysUser.setUserType(Integer.valueOf(role));

        UserContext.setUser(sysUser);
        return true;
    }
}
